package middleware

import (
	"entrytask/facade"
	"entrytask/pkg/rpc"
	"github.com/spf13/viper"
	"log"
	"net"
	"time"
)

var pooledClient *rpc.PooledClient

//func InitPooledClient() {
//	// 2.使用池化客户端,提升性能
//	pooledClient = rpc.NewPooledClient(viper.GetString("rpc_addr"), 200, 200)
//}

// RPCCall rpc single conn call entrance
func RPCCall(method string, fptr interface{}) {
	conn, err := net.DialTimeout("tcp", viper.GetString("rpc_addr"), time.Second)
	if err != nil {
		log.Panic("rpc call fail, ", err)
	}
	// 1.创建普通客户端
	cli := rpc.NewClient(conn)
	cli.CallRPC(method, fptr)

	// 2.使用池化客户端,提升性能, 不能放这里，否则每次都会创建新的线程池导致无限创建链接耗尽系统资源socket
	pooledCli := rpc.NewPooledClient(viper.GetString("rpc_addr"), 200, 200)
	pooledCli.CallPooledRPC(method, fptr)
}

// ConfigRPC rpc pooled call entrance
func ConfigRPC() {
	// 2.使用池化客户端,提升性能
	//pooledClient = rpc.NewPooledClient(viper.GetString("rpc_addr"), 20, 20)
	//pooledClient.CallPooledRPC(method, fptr)
	pooledClient = rpc.NewPooledClient(viper.GetString("rpc_addr"), 200, 200)

	pooledClient.ConfigRemoteMethod(facade.Login, &facade.UserLogin)
	pooledClient.ConfigRemoteMethod(facade.UpdateUser, &facade.UserUpdateInfo)
	pooledClient.ConfigRemoteMethod(facade.QueryName, &facade.UserQueryByName)
	pooledClient.ConfigRemoteMethod(facade.QueryToken, &facade.UserQueryByToken)
}
